<template>
  <view class="ul">
    <view class="li li-title">{{$t('基本信息')}}</view>
    <u-cell-group>
      <u-cell-item
        :arrow="false"
        :value="data_info.name"
        hover-class="none"
        :title="$t('印章名')"
      ></u-cell-item>
      <u-cell-item
        :arrow="false"
        :value="data_info.isOnline === 1 ? data_info.network || '4G' : $t('设备不在线')"
        hover-class="none"
        :title="$t('网络状态')"
      ></u-cell-item>
      <u-cell-item
        v-if="!isOldDingDing(data_info.sn)"
        :arrow="false"
        :value="data_info.fingerPattern ? $t('开启') : $t('关闭')"
        hover-class="none"
        :title="$t('指纹模式')"
      ></u-cell-item>
      <u-cell-item
        v-if="!isOldDingDing(data_info.sn)"
        :arrow="false"
        :value="data_info.sleepTime || `2${$t('分钟')}`"
        hover-class="none"
        :title="$t('休眠时间')"
      ></u-cell-item>
      <u-cell-item
        :arrow="false"
        :value="data_info.bodyId || ''"
        hover-class="none"
        :title="$t('章身ID')"
      ></u-cell-item>
      <u-cell-item
        :arrow="false"
        :value="data_info.uuid"
        hover-class="none"
        :title="$t('印章编号')"
      ></u-cell-item>
      <u-cell-item
        v-if="!isOldDingDing(data_info.sn)"
        :arrow="false"
        :value="data_info.iccid || ''"
        hover-class="none"
        title="ICCID"
      ></u-cell-item>
      <u-cell-item
        :arrow="false"
        :value="data_info.departmentName || ''"
        hover-class="none"
        :title="$t('所属组织')"
      ></u-cell-item>
      <u-cell-item
        :arrow="false"
        :value="data_info.keeperName || $t('暂无')"
        hover-class="none"
        :title="$t('管章人')"
      ></u-cell-item>
      <u-cell-item
        :arrow="false"
        :value="data_info.auditorName || $t('暂无')"
        hover-class="none"
        :title="$t('审计人')"
      ></u-cell-item>
      <u-cell-item
        :label="data_info.location || $t('未定位')"
        :title="$t('当前位置')"
        @click="openLocation"
      ></u-cell-item>
      <u-cell-item
        :arrow="false"
        :value="data_info.typeName || $t('所有章')"
        hover-class="none"
        :title="$t('类别')"
      ></u-cell-item>
      <u-cell-item
        v-if="isOldDingDing(data_info.sn)"
        :arrow="false"
        :value="data_info.softVersion || ''"
        hover-class="none"
        :title="$t('版本号')"
      ></u-cell-item>
      <u-cell-item
        v-if="data_info.migrateDate"
        :arrow="false"
        :value="data_info.migrateDate || ''"
        hover-class="none"
        :title="$t('迁章确认时间')"
      ></u-cell-item>
      <u-cell-item
        v-if="data_info.migrateDate"
        :arrow="false"
        hover-class="none"
        :title="$t('到期剩余天数')"
      >
        <view
          v-if="computedEnd(data_info.migrateDate) > 0"
          slot="right-icon"
          :class="computedEnd(data_info.migrateDate) < 30 ? 'textRed' : ''"
          class="right"
        >
          {{ computedEnd(data_info.migrateDate) }}{{$t('天')}}
        </view>
        <view v-if="computedEnd(data_info.migrateDate) < 0" slot="right-icon" class="right textRed">
          {{$t('已过期')}}{{ Math.abs(computedEnd(data_info.migrateDate)) }}{{$t('天')}}
        </view>
      </u-cell-item>
      <u-cell-item v-if="data_info.fileEntity" :arrow="false" hover-class="none" :title="$t('印章图片')">
        <image
          slot="right-icon"
          :src="`${data_info.fileEntity.fileUrl}?Authorization=${userInfo.token}&us=app`"
          style="width: 80rpx; height: 80rpx"
          @click="enlarge(`${data_info.fileEntity.fileUrl}?Authorization=${userInfo.token}`)"
        ></image>
      </u-cell-item>
    </u-cell-group>
    <view class="li li-title">{{$t('远程控制')}}</view>
    <u-cell-group>
      <u-cell-item
        v-if="!isOldDingDing(data_info.sn)"
        :value="
          data_info.sleepTime
            ? picker.sleepTime[data_info.sleepTime - 2 < 0 ? 0 : data_info.sleepTime - 2].label
            : `2${$t('分钟')}`
        "
        :title="$t('休眠时间')"
        @click="navigetPage('休眠时间')"
      ></u-cell-item>
      <u-cell-item
        v-if="isOldDingDing(data_info.sn)"
        :value="computedlockTime(data_info.lockTime)"
        :title="$t('自动上锁时间')"
        @click="navigetPage('自动上锁时间')"
      ></u-cell-item>
      <u-cell-item
        v-show="!isOldDingDing(data_info.sn) && userInfo.ocrEnabled"
        :arrow="false"
        :title="$t('高拍仪')"
      >
        <u-switch
          slot="right-icon"
          v-model="data_info.bluetooth"
          :active-value="0"
          :inactive-value="1"
          @change="navigetPage('高拍仪')"
        ></u-switch>
      </u-cell-item>
      <u-cell-item :arrow="false" :title="$t('远程锁定')">
        <u-switch
          slot="right-icon"
          v-model="data_info.status"
          :active-value="4"
          :inactive-value="0"
          @change="navigetPage('远程锁定')"
        ></u-switch>
      </u-cell-item>
      <u-cell-item v-if="!isOldDingDing(data_info.sn)" :arrow="false" :title="$t('指纹模式')">
        <u-switch
          slot="right-icon"
          v-model="data_info.fingerPattern"
          :active-value="4"
          :inactive-value="0"
          @change="navigetPage('指纹模式')"
        ></u-switch>
      </u-cell-item>
      <u-cell-item :arrow="false" :title="$t('摄像头')">
        <u-switch
          v-model="data_info.camera"
          :active-value="0"
          :inactive-value="1"
          @change="navigetPage('摄像头')"
        ></u-switch>
      </u-cell-item>
      <u-cell-item
        v-if="!isOldDingDing(data_info.sn)"
        :title="$t('wifi列表')"
        @click="navigetPage('wifi列表')"
      ></u-cell-item>
      <u-cell-item
        v-if="!isOldDingDing(data_info.sn)"
        :title="$t('安装印章')"
        @click="navigetPage('安装印章')"
      ></u-cell-item>
      <u-cell-item
        v-if="data_info.remoteUseFlag"
        :title="$t('远程用印')"
        @click="navigetPage('远程用印')"
      ></u-cell-item>
    </u-cell-group>
    <templete v-if="isNewDingDing(data_info.sn)">
      <view class="li li-title">{{$t('蓝牙控制')}}</view>
      <u-cell-group>
        <u-cell-item :title="$t('wifi设置')" @click="wifiSetHandle"></u-cell-item>
        <u-cell-item :title="$t('远程开锁')" @click="remoteUnlocking"></u-cell-item>
      </u-cell-group>
    </templete>

    <u-picker
      v-model="picker.show"
      :default-selector="[data_info.sleepTime ? data_info.sleepTime - 2 : 0]"
      :range="picker.sleepTime"
      mode="selector"
      range-key="label"
      @cancel="close"
      @confirm="bindPickerChange2"
    ></u-picker>
    <u-picker
      v-model="lock.show"
      :default-selector="[0]"
      :range="lock.lockTime"
      mode="selector"
      range-key="label"
      @cancel="close"
      @confirm="bindPickerlock"
    ></u-picker>
    <!-- <view class="li" >
      <view class="left">加密方式：</view>
      <view class="right">正在开发中...</view>
    </view> -->
    <!-- <button @click="requestPayment">支付宝支付</button> -->
    <u-modal
      v-model="modal.show"
      :confirm-text="$t('解锁')"
      show-cancel-button
      :title="$t('远程用印')"
      @confirm="confirmModal"
    >
      <view class="modalcontent">
        {{$t('加盖次数')}}：
        <u-number-box v-model="modal.count" :min="1"></u-number-box>
      </view>
    </u-modal>
    <!--  弹出层  -->
    <uni-popup ref="pickerWifiPopup" :custom="true" :mask-click="true" type="center">
      <view class="uni-tip">
        <text>{{$t('选择wifi')}}</text>
        <u-form ref="wifiForm" :model="wifiForm">
          <u-form-item label="WIFI" prop="ssid" required>
            <u-input v-model="wifiForm.ssid" />
          </u-form-item>
          <u-form-item :label="$t('密码')" required>
            <u-input v-model="wifiForm.pwd" type="password" />
          </u-form-item>
        </u-form>
        <u-button type="primary" @click="pickerWifiConfirm">{{$t('确定')}}</u-button>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'
import bluetooth from '../../../common/function/bluetooth'
import utils from '../../../utils/utils'
import CODE from '@uni-plugs/uni-code'
import deviceType from '../../../utils/deviceType'

export default {
  computed: {
    ...mapGetters(['Bluetooth', 'userInfo', 'api']),
    computedEnd() {
      return (item) => {
        let data = new Date(item).getTime()
        let newData = new Date().getTime()
        return 365 - new Date(newData - data).getDate()
      }
    },
    isOldDingDing() {
      return (sn) => deviceType(sn).key === 'DT'
    },
    isNewDingDing() {
      return (sn) => deviceType(sn).key === 'DP'
    },
    computedlockTime() {
      return (lockTime) => {
        if (lockTime === 60) {
          return '1' + this.$t('分钟')
        } else if (lockTime === 180) {
          return '3' + this.$t('分钟')
        } else if (lockTime === 600) {
          return '10' + this.$t('分钟')
        } else if (lockTime === 1800) {
          return '30' + this.$t('分钟')
        } else {
          return '1' + this.$t('分钟')
        }
      }
    }
  },
  data() {
    return {
      id: '', //章的id
      enlarge_img_url: [], //放大图片
      data_info: {}, //详情数据
      //远程控制
      picker: {
        show: false,
        sleepTime: [
          {
            //印章状态的内容
            label: '2' + this.$t('分钟'),
            value: 2
          },
          {
            label: '3' + this.$t('分钟'),
            value: 3
          },
          {
            label: '4' + this.$t('分钟'),
            value: 4
          },
          {
            label: '5' + this.$t('分钟'),
            value: 5
          },
          {
            label: '6' + this.$t('分钟'),
            value: 6
          },
          {
            label: '7' + this.$t('分钟'),
            value: 7
          },
          {
            label: '8' + this.$t('分钟'),
            value: 8
          },
          {
            label: '9' + this.$t('分钟'),
            value: 9
          },
          {
            label: '10' + this.$t('分钟'),
            value: 10
          }
        ]
      },
      lock: {
        show: false,
        lockTime: [
          {
            //印章状态的内容
            label: '1' + this.$t('分钟'),
            value: 60
          },
          {
            label: '3' + this.$t('分钟'),
            value: 180
          },
          {
            label: '10' + this.$t('分钟'),
            value: 600
          },
          {
            label: '30' + this.$t('分钟'),
            value: 1800
          }
        ]
      },
      modal: {
        show: false,
        count: 1
      },
      wifiForm: {
        //已选择的值
        pwd: '',
        ssid: ''
      }
    }
  },
  onLoad(e) {
    uni.setNavigationBarTitle({title: this.$t('印章详情')})
    //console.log('onLoad', e)
    this.id = e.id
    // uni.getProvider({
    //    service: "payment",
    //     success: function (res) {
    //         //console.log('获取支付通道',res.provider)
    //     },
    // 	fail(e) {
    // 		//console.log("获取支付通道失败：", e);
    // 	}
    // });
    //
  },
  onShow() {
    //获取当前页面的数据
    this.get_data()
  },
  //监听头部导航编辑事件
  onNavigationBarButtonTap(e) {
    if (e.index === 0) {
      //编辑
      //点击完成
      uni.navigateTo({
        url: '../sealEditor/sealEditor?deviceid=' + this.id
      })
    }
  },
  methods: {
    ...mapMutations(['set_BlueToothActiveBle', 'set_BlueToothDeviceInfo']),
    // 远程开锁
    async remoteUnlocking() {
      await this.bluetoothConnectDevice()
      // 发送指令
      const result = await bluetooth.sendBluetoothCmd({ data: 'DeviceUnlock', type: 'in' })
      //console.log('result', result)
      if (result.success) {
        utils.toast(this.$t('开锁成功'))
      } else {
        utils.toast(result.msg)
      }
    },
    wifiSetHandle() {
      this.$refs.pickerWifiPopup.open()
    },
    // 确认设置wifi
    async pickerWifiConfirm() {
      //console.log('pickerWifiConfirm', this.wifiForm)
      const { ssid, pwd } = this.wifiForm
      if (!pwd || !ssid) {
        utils.toast(this.$t('输入错误'))
        return
      }
      await this.bluetoothConnectDevice()
      // 发送指令
      const result = await bluetooth.sendBluetoothCmd({
        data: {
          ssid,
          pwd,
          encryption: ''
        },
        type: 'wf'
      })
      //console.log('result', result)
      if (result.success) {
        utils.toast(this.$t('设置wifi成功'))
      } else {
        utils.toast(result.msg)
      }
    },
    // 蓝牙连接设备
    async bluetoothConnectDevice() {
      return new Promise(async (resolve, reject) => {
        bluetooth.init((initRes) => {
          bluetooth.startBluetoothDevicesDiscovery(async (discovery) => {
            //console.log('查找设备', discovery)
          })
        })
        uni.showToast({ title: this.$t('正在配对') + '...', icon: 'none', mask: true, duration: 5000 })
        await new Promise((resolve) => setTimeout(resolve, 5000))
        await bluetooth.stopBluetoothDevicesDiscovery()
        bluetooth.getBluetoothDevices(async (res) => {
          //console.log('已发现的蓝牙设备', res)
          const devices = res
            .filter((d) => d.advertisServiceUUIDs[0] === '0000FE00-0000-1000-8000-00805F9B34FB')
            .map((d) => {
              let ManufacturerData = parseInt(utils.ab2hex(d.advertisData))
              const deviceIdString = utils.hexToStr('' + ManufacturerData)
              return {
                ...d,
                deviceIdString,
                _advertisData: parseInt(utils.ab2hex(d.advertisData))
              }
            })
          const curDevice = devices.find((d) => d.deviceIdString === this.id)
          //console.log('curDevice', curDevice)
          if (!curDevice) {
            resolve()
            return
          }
          this.set_BlueToothActiveBle(curDevice)
          // 找到了当前的设备，连接设备
          await bluetooth.createBLEConnection(
            async (activeBle) => {
              //已连接。并获取到可写可监听的特征值成功
              //console.log('已连接。并获取到可写可监听的特征值成功')
              //启动监听
              bluetooth.onBLEConnectionStateChange()
              //开启蓝牙监听
              bluetooth.readBLECharacteristicValue()
              resolve()
            },
            (err) => {
              console.error('连接设备失败', err)
              if (err === -1) {
                uni.closeBluetoothAdapter()
              }
              utils.toast(this.$t('未找到此设备'))
              reject('未找到此设备')
            }
          )
        })
      })
    },
    //远程用印
    confirmModal() {
      let req = {
        deviceId: this.data_info.id,
        count: this.modal.count
      }
      this.$u.post(this.api.GLOBAL_device_signet_remoteUnlock, req).then((res) => {
        if (res.code === 200) {
          uni.showToast({
            title: this.$t(res.msg),
            icon: 'none',
            duration: 2000
          })
        }
      })
    },
    close(value) {
      //获取当前页面的数据
      this.get_data()
    },
    navigetPage(title) {
      //console.log(title);
      uni.showLoading({
        title: '指令下发中...',
        mask: false
      })
      if (title === '远程锁定') {
        //console.log(8888);
        //选取印章状态(远程锁定)
        this.bindPickerChange()
      } else if (title === '指纹模式') {
        //指纹模式
        this.bindPickerChange3()
      } else if (title === '摄像头') {
        //摄像头
        this.bindPickerChange4()
      } else if (title === '休眠时间') {
        uni.hideLoading()
        this.picker.show = true
      } else if (title === 'wifi列表') {
        this.wifi_list()
      } else if (title === '安装印章') {
        this.remoteLoading()
      } else if (title === '高拍仪') {
        this.ocrSwitch()
      } else if (title === '自动上锁时间') {
        uni.hideLoading()
        this.lock.show = true
      } else if (title === '远程用印') {
        this.modal.show = true
        uni.hideLoading()
      }
    },
    ocrSwitch() {
      let status = this.data_info.ocr ? 0 : 1
      let req = {
        deviceId: this.data_info.id,
        status: status //0开启 4：锁定
      }
      this.$u
        .post(this.api.GLOBAL_device_signet_switchHighProfileCamera, req)
        .then((res) => {
          if (res.code === 200) {
            uni.showToast({
              title: this.$t(res.msg),
              icon: 'none',
              duration: 2000
            })
          } else {
            this.get_data()
          }
        })
        .catch((err) => {
          this.get_data()
        })
    },
    //wifi
    wifi_list() {
      uni.navigateTo({
        url: '../wifiList/wifiList?deviceid=' + this.id
      })
    },
    //地图查看印章位置
    openLocation() {
      if (this.data_info.latitude) {
        uni.openLocation({
          longitude: Number(this.data_info.longitude),
          latitude: Number(this.data_info.latitude),
          name: this.data_info.name,
          address: this.data_info.location
        })
      } else {
        uni.showToast({
          title: this.$t('暂未获取到经纬度'),
          icon: 'none',
          duration: 2000
        })
      }
    },
    //远程装章
    remoteLoading() {
      this.$u
        .post(this.api.GLOBAL_device_signet_installationChapterHead, { signetId: this.id })
        .then((res) => {
          if (res.code === 200) {
            uni.showToast({
              title: this.$t(res.msg),
              icon: 'none',
              duration: 2000
            })
          }
        })
    },
    //选取印章状态(远程锁定)
    bindPickerChange() {
      let status = this.data_info.status ? 4 : 0
      let req = {
        signetId: this.data_info.id,
        status: status //0解锁 4：锁定
      }
      this.$u.post(this.api.GLOBAL_device_signet_setRemoteLock, req).then((res) => {
        if (res.code === 200) {
          uni.showToast({
            title: this.$t(res.msg),
            icon: 'none',
            duration: 2000
          })
        } else {
          this.data_info.status = !this.data_info.status
        }
      })
    },
    //自动上锁时间
    bindPickerlock(e) {
      uni.showLoading({
        title: this.$t('指令下发中') + '...',
        mask: false
      })
      let req = {
        deviceId: this.data_info.id,
        lockTime: this.lock.lockTime[e[0]].value
      }
      this.$u
        .post(this.api.GLOBAL_device_dingSignet_updateDeviceAutoLockSeconds, req)
        .then((res) => {
          if (res.code === 200) {
            uni.showToast({
              title: this.$t(res.msg),
              icon: 'none',
              duration: 2000
            })
            this.get_data()
          }
        })
    },
    //选取休眠时间
    bindPickerChange2(e) {
      uni.showLoading({
        title: this.$t('指令下发中') + '...',
        mask: false
      })
      this.data_info.sleepTime = this.picker.sleepTime[e[0] < 0 ? 0 : e[0]].value
      let req = {
        signetId: this.data_info.id,
        value: this.data_info.sleepTime
      }
      this.$u.post(this.api.GLOBAL_device_signet_setDormancy, req).then((res) => {
        if (res.code === 200) {
          uni.showToast({
            title: this.$t(res.msg),
            icon: 'none',
            duration: 2000
          })
        } else {
          this.close()
        }
      })
    },
    //指纹模式
    bindPickerChange3() {
      let status = this.data_info.fingerPattern ? 1 : 0 //指纹模式 1：开启 0：关闭
      let req = {
        signetId: this.data_info.id,
        status: status
      }
      this.$u.post(this.api.GLOBAL_device_signet_openPatternFinger, req).then((res) => {
        if (res.code === 200) {
          uni.showToast({
            title: this.$t(res.msg),
            icon: 'none',
            duration: 2000
          })
        } else {
          this.data_info.fingerPattern = !this.data_info.fingerPattern
        }
      })
    },
    //摄像头
    bindPickerChange4(e) {
      let status = this.data_info.camera ? 0 : 1 //摄像头 0：开启 1：关闭
      let req = {
        deviceId: this.data_info.id,
        status: status
      }
      this.$u.post(this.api.GLOBAL_device_signet_cameraSwitch, req).then((res) => {
        if (res.code === 200) {
          uni.showToast({
            title: this.$t(res.msg),
            icon: 'none',
            duration: 2000
          })
        } else {
          this.data_info.camera = !this.data_info.camera
        }
      })
    },
    //获取当前页面的数据
    get_data() {
      this.$u.post(this.api.GLOBAL_signet_getBySignet, { signetId: this.id }).then((res) => {
        if (res.code === 200) {
          //console.log('GLOBAL_signet_getBySignet', res.data);
          //console.log('设备型号', deviceType(res.data.sn))
          res.data.status = res.data.status === 4
          res.data.fingerPattern = res.data.fingerPattern === 1
          res.data.camera = res.data.camera === 0
          res.data.ocr = res.data.ocr === 0
          this.data_info = res.data
        } else {
          setTimeout(() => {
            uni.navigateBack({
              delta: 1
            })
          }, 2000)
        }
      })
    },
    enlarge(img) {
      this.enlarge_img_url[0] = img
      uni.previewImage({
        urls: this.enlarge_img_url
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.ul {
  width: 100%;
  height: 100%;
  font-size: 30upx;
  box-sizing: border-box;

  .li-title {
    color: #9f9f9f;
    background: #f5f5f5;
    width: 100%;
  }

  .li {
    display: flex;
    justify-content: space-between;
    padding: 20upx 40upx;
    box-sizing: border-box;
    border-bottom: 2rpx solid #f2f2f2;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;

    .left {
      font-size: 32upx;
    }

    .right {
      color: #666666;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .right_bq {
      border: 2rpx solid #009bde;
      background-color: #61b4e4;
      border-radius: 5upx;
      padding: 0 15upx;
      font-size: 24upx;
      color: #fff;
      height: 40upx;
      line-height: 40upx;
      margin-top: 6upx;
    }

    .picker {
      .right {
        display: flex;
        color: #888;

        .iconfont {
          margin: 6rpx 0 0 20rpx;
        }
      }
    }

    .wifi {
      display: flex;
      color: #888;

      .iconfont {
        margin: 6rpx 0 0 20rpx;
      }
    }
  }

  .li_img {
    display: flex;
    line-height: 100upx;
    padding: 15upx 40upx;
    border-bottom: 2rpx solid #f2f2f2;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    box-sizing: border-box;

    image {
      width: 100upx;
      height: 100upx;
      border-radius: 10rpx;
    }
  }

  .btn {
    display: flex;
    position: fixed;
    bottom: 0upx;
    padding: 10upx;
    justify-content: space-around;
    width: 100%;
    color: #fff;
    border-top: 1px solid #f2f2f2;
    background: #fff;
    box-sizing: border-box;

    view {
      width: 200upx;
      height: 80upx;
      line-height: 80upx;
      text-align: center;
      border-radius: 10upx;
      transform: scale(0.8);
    }

    .btn_1 {
      background-color: #009bde;
    }

    .btn_2 {
      background-color: red;
    }

    .btn_3 {
      background-color: #3cb371;
    }
  }

  .textRed {
    color: red !important;
  }
}

.modalcontent {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
}

/* 提示窗口 */
.uni-tip {
  padding: 15px;
  width: 300px;
  background: #fff;
  box-sizing: border-box;
  border-radius: 10px;
}

.uni-tip-title {
  text-align: center;
  font-weight: bold;
  font-size: 16px;
  color: #333;
}
</style>
